import os.path
from typing import Union
import uvicorn
from fastapi import FastAPI
from fastapi.responses import StreamingResponse

from imd import web_query_maintance
from post import query_json, upload_result

app = FastAPI()


@app.get('/')
def read_root():
    return {'Hello': 'World'}


@app.get('/items/{item_id')
def read_item(item_id: int, q: Union[str, None] = None):
    return {'item_id': item_id, 'q': q}


'''
@ parameter 
id
maintainDept
maintainDeptName
roadNo
roadName
startingStation
roadLen
duration
budgetFee
trafficLevel
inTime
upTime
endingStation
lineTotal
sectionRoad
'''

@app.get('/single')
def read_single(cls: str, dept: str, roadNo: str):
    print('Read type: {}, dept: {}, roadNo: {}'.format(cls, dept, roadNo))
    params = query_json(dept, roadNo)
    print(params)
    results = {}
    status = []
    for p in params:
        maintainDept = p['maintainDept']
        roadNo = p['roadNo']
        startingStation = p['startingStation']
        roadLen = p['roadLen']
        duration = p['duration']
        budgetFee = p['budgetFee']
        trafficLevel = p['trafficLevel']
        lineTotal = p['lineTotal']
        print('maintainDept: {}, roadNo: {}, startingStation: {}, roadLen: {}, duration: {}, budgetFee: {}, trafficLevel: {}'.format(maintainDept, roadNo, startingStation, roadLen, duration, budgetFee, trafficLevel))

        # upload result
        tmp = {}
        filepath = web_query_maintance(maintainDept, roadNo, startingStation, roadLen, duration, budgetFee, trafficLevel, lineTotal)
        if os.path.exists(filepath):
            res = upload_result(filepath, startingStation)
            print(res.status_code)
            tmp['filename'] = filepath
            tmp['code'] = res.status_code
            status.append(tmp)
    results['status'] = status
    return results

    #
    # p = params[0]
    # maintainDept = p['maintainDept']
    # roadNo = p['roadNo']
    # roadLen = p['roadLen']
    # duration = p['duration']
    # budgetFee = p['budgetFee']
    # trafficLevel = p['trafficLevel']
    # lineTotal = p['lineTotal']
    #
    # filepath = web_query_maintance(maintainDept, roadNo, startingStation, roadLen, duration, budgetFee, trafficLevel, lineTotal)
    # if os.path.exists(filepath):
    #     res = upload_result(filepath, startingStation)
    #     print(res)
    #     return StreamingResponse(open(filepath, encoding='utf-8'))
    # # return params


if __name__ == '__main__':
    # 启动服务
    uvicorn.run(app, host='0.0.0.0', port=8800)
